<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use app\api\model\UserClaimAddress;
use app\api\model\YaoqingRecords;
use think\Db;
use think\Validate;

class Flag extends Common {
    public function list() {
        $paystate = input('paystate/d', 0);
        if ($paystate) {
            if ($paystate == 1) {
                $where = ['paystate' => 1, 'price' => ['<>', 0]];
            } elseif ($paystate == 2) {
                $where = ['paystate' => 1, 'price' => 0];
            } elseif ($paystate == 3) {
                $where = ['paystate' => 0];
            }
        }
        $this->assign('paystate', $paystate);

        $status          = input('status/d', 0);
        $where['status'] = $status;
        $this->assign('status', $status);

        $search_type = input('param.search_typeid');
        $search_name = input('param.search_name');
        if ($search_name) {
            if (in_array($search_type, ['user_id', 'number'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $this->assign('search', $search_type);
        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } elseif ($order == 2) {
            $order = 'asc';
        }

        $data = Db::name('user_flag')
            ->where($where)
            ->order('id ' . $order)
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                $user             = _user_cache($item['user_id']);
                $item['username'] = $user['name'];
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function dele() {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $res = Db::name('user_flag')->where(['id' => $id])->find();
                if ($res['status'] == 0) {
                    $timenow = time();
                    $db = Db::name('user_flag')->where(['id' => $id])->update(['status' => -1, 'update_time' => $timenow]);
                    if ($db && $res['price'] > 0) {
                        Db::name('flag_expire')->insert([
                            'flag_id' => $res['id'],
                            'price' => $res['price'],
                            'score' => $res['price'] * 5,
                            'create_time'=>$timenow
                        ]);
                    }
                } elseif ($res['status'] == -1) {
                    $db = Db::name('user_flag')->where(['id' => $id])->delete();
                } else {
                    $db = false;
                }
                if ($db) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * @return mixed
     */
    public function content() {
        $where       = [];
        $search_type = input('param.search_type');
        $search_name = input('param.search_name');
        if ($search_name) {
            if (in_array($search_type, ['user_id', 'flag_id', 'id'])) {
                $where['t1.' . $search_type] = $search_name;
            } else {
                $where['t1.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } elseif ($order == 2) {
            $order = 'asc';
        }

        $cate             = input('cate', 1);
        $where['t1.cate'] = $cate;
        $this->assign('cate', $cate);

        $data = Db::name('flags t1')
            ->field('t1.*, t2.name username, t2.phone')
            ->join('user t2', 't2.id = t1.user_id', 'LEFT')
            ->where($where)
            ->order('t1.id ' . $order)
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                $item['images'] = $item['images'] ? explode(',', $item['images']) : [];
                $item['days']   = Db::name('user_flag')->where(['id' => $item['flag_id']])->cache(60)->value('days');
                $item['fed_pass']   = Db::name('flag_fed')->where(['flags_id'=>$item['id'], 'fed'=>1])->count();
                $item['fed_miss']   = Db::name('flag_fed')->where(['flags_id'=>$item['id'], 'fed'=>2])->count();
                return $item;
            });

        $page = $data->render();
        $this->assign('search_type', $search_type);
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function delecontent() {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $res = Db::name('flags')->where(['id' => $id])->find();
                $db  = Db::name('flags')->delete($id);
                if ($db) {
                    $images = [];
                    if ($res['images']) {
                        $images = explode(',', $res['images']);
                    }
                    $images = array_unique($images);
                    foreach ($images as $key => $value) {
                        \app\service\AliOss::delete($value);
                    }
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * @return mixed
     */
    public function category() {
        $category = Db::name('category_of_flag')->order('sort desc,id desc')->select();
        $this->assign('data', $category);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function addcategory() {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            //开始验证
            $validate = new Validate([
                ['title', 'require|max:30', '名称不能为空|长度不能超过30字符'],
            ]);

            $data = [
                'title' => $post['title'],
            ];

            $time = time();
            if ($validate->check($data)) {
                if (!$id) {
                    //添加数据
                    $typename = db('category_of_flag')->where(['title' => $post['title']])->find();
                    if ($typename) {
                        return ['err' => '名称已存在'];
                    }
                    $post['create_time'] = $time;
                    $post['update_time'] = $time;

                    $res = db('category_of_flag')->insert($post);
                    if ($res) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {
                    //修改数据
                    $post['update_time'] = $time;
                    $res                 = db('category_of_flag')->where('id', $id)->update($post);
                    if ($res) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = db('category_of_flag')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function delecate() {
        if (request()->isAjax()) {

            $id = input('post.id/d');
            if (!$id) {
                return json(["err" => "参数错误1"]);
                exit();
            }
            $del = Db::name('category_of_flag')->delete($id);
            if ($del) {
                $data = ["ret" => '删除成功'];
            } else {
                $data = ["err" => '删除失败'];
            }
        } else {
            $data = ["err" => "参数错误2"];
        }
        return json($data);
    }

    /**
     * @return mixed
     */
    public function recommend() {
        $where       = [];
        $search_type = input('param.search');
        $search_name = input('param.name');
        if ($search_name) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }
        $data = Db::name('flag_recommend')->where($where)->order('sort desc,id desc')->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item) {
            $item['catename'] = Db::name('category_of_flag')->cache(60)->where(['id' => $item['cate_id']])->value('title');
            return $item;
        });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function addrecommend() {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            //开始验证
            $validate = new Validate([
                ['title', 'require|max:30', '名称不能为空|长度不能超过30字符'],
            ]);

            $data = [
                'title' => $post['title'],
            ];

            if ($validate->check($data)) {
                if (!$id) {
                    //添加数据
                    $typename = db('flag_recommend')->where(['title' => $post['title']])->find();
                    if ($typename) {
                        return ['err' => '内容已存在'];
                    }
                    $time = time();
                    $res  = db('flag_recommend')->insert($post);
                    if ($res) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {
                    //修改数据
                    $res = db('flag_recommend')->where('id', $id)->update($post);
                    if ($res) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = db('flag_recommend')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $category = Db::name('category_of_flag')->order('sort desc,id desc')->select();
            $this->assign('category', $category);

            $data = $this->fetch();
        }

        return $data;
    }

    public function delerecommend() {
        if (request()->isAjax()) {

            $id = input('post.id/d');
            if (!$id) {
                return json(["err" => "参数错误1"]);
                exit();
            }
            $del = Db::name('flag_recommend')->delete($id);
            if ($del) {
                $data = ["ret" => '删除成功'];
            } else {
                $data = ["err" => '删除失败'];
            }
        } else {
            $data = ["err" => "参数错误2"];
        }
        return json($data);
    }

    /**
     * @return mixed
     */
    public function comment() {
        $where = [];
        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } elseif ($order == 2) {
            $order = 'asc';
        }
        $search_type = input('param.search_type');
        $search_name = input('param.search_name');
        if ($search_name) {
            if (in_array($search_type, ['user_id', 'flags_id'])) {
                $where['t1.' . $search_type] = $search_name;
            } else {
                $where['t1.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = Db::name('flag_comments t1')->field('t1.*, t2.name username, t2.phone')->join('user t2', 't2.id = t1.user_id')->where($where)->order('t1.id ' . $order)->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();

        $this->assign('search_type', $search_type);
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function delecomment() {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $flag_comments = Db::name('flag_comments')->where(['id' => ['in', $id]])->group('flags_id')->column('flags_id');
                $db            = Db::name('flag_comments')->delete($id);
                if ($db) {
                    foreach ($flag_comments as $key => $value) {
                        try {
                            $count = Db::name('flag_comments')->where(['flags_id' => $value])->count();
                            Db::name('flags')->where(['id' => $value])->setField('comments', $count);
                        } catch (\Exception $e) {

                        }
                    }
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * @return mixed
     */
    public function supervises() {
        $where       = [];
        $search_type = input('param.search');
        $search_name = input('param.name');
        if ($search_name) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }
        $data = Db::name('flag_supervise')
            ->where($where)
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item) {
            $item['flagInfo'] = Db::name('user_flag')->cache(10)->where(['id' => $item['flag_id']])->find();
            $item['userInfo'] = _user_cache($item['user_id']);
            return $item;
        });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function add() {
        $id = input("id");
        if (request()->isAjax()) {
            $post = input('post.');

            if (!$post['user_id']) {
                return ['err' => '请填写发布用户'];
            }
            $user = Db::name('user')->where(['id'=>$post['user_id'], 'delete_time'=>0, 'reg'=>1])->find();
            if (!$user) return ['err'=>'用户异常'];
            if (!$post['content']) {
                return ['err' => '内容必填'];
            }
            if (!$post['days']) {
                return ['err' => '打卡天数必填'];
            }
            if ($post['price'] > 999) {
                return ['err' => 'Flag当前可填写金额最大为 999'];
            }
            $timenow             = time();
            $post['start_date']  = $post['start_date'] == 1 ? date('Y-m-d') : date('Y-m-d', $timenow + 86400);
            $post['end_time']    = strtotime($post['start_date']) + 86399;
            $post['create_time'] = $timenow;
            $post['update_time'] = $timenow;
            $post['paystate']    = 1;
            $post['askfornum']   = 1;
            $db                  = Db::name('user_flag')->insert($post);
            if ($db) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    /**
     * @return mixed
     */
    public function addsign() {
        $id = input("id");
        if (request()->isAjax()) {
            $post = input('post.');

            $flag_id  = input('id');
            $content  = $post['content'];
            $images   = $post['cover'];
            $video    = $post['video'];
            $timenow  = time();
            $flagInfo = Db::name('user_flag')->where(['id' => $flag_id])->find();
            $userInfo = Db::name('user')->find($flagInfo['user_id']);
            if (!$flagInfo || !$flagInfo['paystate']) {
                return ['err' => '打卡失败'];
            }
            if ($flagInfo['status'] != 0) {
                return ['err' => 'flag已结束'];
            }
            if (strtotime($flagInfo['start_date']) > $timenow) {
                return ['err' => '未到打卡时间'];
            }
            $signcount = $flagInfo['signday'];
            if ($signcount >= $flagInfo['days']) {
                return ['err' => '超出打卡天数'];
            }
            if ($flagInfo['signtime'] > strtotime(date('Y-m-d'))) {
                return ['err' => '今日已打卡'];
            }
            $result = Db::name('flags')->insertGetId([
                'user_id'     => $userInfo['id'],
                'flag_id'     => $flag_id,
                'content'     => $content,
                'day'         => ++$signcount,
                'images'      => $images,
                'private'     => $flagInfo['price'] > 0 ? 0 : 1,
                'create_time' => $timenow,
                'city'        => $userInfo['city'],
                'cate'        => 1,
                'type'        => 2,
                'video'       => $video,
            ]);
            if ($result) {
                $data = ['id' => $result, 'finish' => 1, 'score' => 0];
                if ($signcount == $flagInfo['days']) {
                    Db::name('user_flag')->where(['id' => $flag_id])->update(['status' => 1, 'update_time' => $timenow, 'signtime' => $timenow, 'signday' => Db::raw('signday+1')]);
                    if ($flagInfo['price']) {
                        // 返回积分
                        $data['score'] = $flagInfo['price'] * 5;
                        YaoqingRecords::index($flagInfo['user_id'], 0, $data['score'], 'Flag坚持打卡成功 ', 1);
                    }
                    Privatechat::notice($flagInfo['user_id'], '您的Flag【' . $flagInfo['content'] . '】坚持打卡成功');
                } else {
                    Db::name('user_flag')->where(['id' => $flag_id])->update([
                        'end_time' => Db::raw('end_time+86400'),
                        'signtime' => $timenow,
                        'signday'  => Db::raw('signday+1'),
                    ]);
                }
                if ($flagInfo['claim_address_id']) {
                    Db::name('user_claim_address')->where(['id' => $flagInfo['claim_address_id']])->setInc('sign');
                    UserClaimAddress::sendredpacket($flagInfo['claim_address_id'], $flagInfo['user_id']);
                }
                return ['ret' => '打卡成功'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }
    /**
     * @return mixed
     */
    public function fed() {
        $where       = [];
        $search_type = input('param.search_type');
        $search_name = input('param.search_name');
        if ($search_name) {
            if (in_array($search_type, ['user_id', 'flags_id'])) {
                $where['t1.' . $search_type] = $search_name;
            } else {
                $where['t1.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } elseif ($order == 2) {
            $order = 'asc';
        }

        $fed = input('fed');
        if ($fed) {
            $where['fed'] = $fed;
            $this->assign('fed', $fed);
        }

        $data = Db::name('flag_fed t1')
            ->field('t1.*, t2.name username, t2.phone')
            ->join('user t2', 't2.id = t1.user_id', 'LEFT')
            ->where($where)
            ->order('t1.id ' . $order)
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                return $item;
            });

        $page = $data->render();
        $this->assign('search', $search_type);
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }
}